package rms.mall.server.application.service;

import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Component;
import rms.mall.server.api.enums.ErrorCode;
import rms.mall.server.api.module.system.LoginReq;
import rms.mall.server.api.module.system.QueryAcctReq;
import rms.mall.server.domain.exception.BizException;
import rms.mall.server.domain.repository.system.AcctInfoRepository;
import rms.mall.server.domain.entity.system.AcctInfo;

import javax.annotation.Resource;
import java.util.Objects;

@Component
public class LoginService {

    @Resource
    private AcctInfoRepository acctInfoRepository;


    public String loginByPassword(LoginReq req) {
        AcctInfo acctInfo = acctInfoRepository.getOne(Wrappers.<AcctInfo>lambdaQuery().eq(AcctInfo::getUserName,req.getUserName()));
        if (Objects.isNull(acctInfo)) {
            throw new BizException(ErrorCode.PARAM_ERROR.getCode(), "请输入正确的账号");
        }
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        if (!passwordEncoder.matches(req.getPassword(), acctInfo.getPassword())) {
            throw new BizException(ErrorCode.PARAM_ERROR.getCode(), "请输入正确的密码");
        }
        StpUtil.login(acctInfo.getId());
        return StpUtil.getTokenValue();
    }
}
